import 'dart:io';

/// CreateTime 2020/6/9 9:55
/// CreateUser chen 
/// ProjectName flutter_elf
import 'package:flutter_elf/config/component_index.dart';
import 'package:html/dom.dart';
import 'package:html/parser.dart';
import 'package:http/http.dart'as http;

import '../download/file_utils.dart';

int totalPage = 135;
String url = 'http://jandan.net/ooxx';
void main()async{
  var response = await http.Client().get(Uri.parse(url));
  File file = await FileUtils.getFile('test/html_parser/cache2.txt');
  for (int i = 0; i < 135; i++) {
      writeFile(file, getList(response).join('\n') + '\n');
      await Future.delayed(Duration(milliseconds: 500));
      response = await http.Client().get(Uri.parse(getNextPage(response)));
      print('i======>$i');
  }

  await Future.delayed(Duration(seconds: 1000));
}


writeFile(File file,String str){
  print('写入');
  return file.writeAsString(str,mode:FileMode.append);
}

//Older Comments
String getNextPage(http.Response response){
  if(response.statusCode == 200){
    Document document = parse(response.body);
    return 'http:' + document.getElementsByClassName('previous-comment-page')[0].attributes['href'];
  }else{
    print('网络请求错误');
    throw Exception();
  }
}

List<String> getList(http.Response res){
  if(res.statusCode == 200){
    final docu = parse(res.body);
    return docu.getElementsByClassName('view_img_link').map((img){
      return 'http:' + img.attributes['href'];
    }).toList();
  }else{
    print('网络请求错误');
    throw Exception();
  }
}
